package server;

import java.util.LinkedList;

import twitter4j.FilterQuery;
import twitter4j.TwitterException;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;

public class ConnectionManager {
	private TwitterStream stream;
	private StatusStack stack;
	private TagStack tags;
	private TweetParser parser;

	public ConnectionManager(TweetParser parser) {
		this.stack = parser.getStack();
		this.tags = new TagStack();
		this.parser = parser;
		stream = new TwitterStreamFactory()
				.getInstance("tweetmetoo", "eci2007");
		TwitterListenner listener = new TwitterListenner(stack);
		stream.setStatusListener(listener);
	}

	private LinkedList<String> merge(LinkedList<String> newtags, boolean add) {
		LinkedList<String> ori = tags.getlistStack();
		int rangeori = ori.size();
		int rangenew = newtags.size();
		newtags: for (int i = 0; i < rangenew; i++) {
			for (int j = 0; j < rangeori; j++) {
				if ((ori.get(j)).equalsIgnoreCase(newtags.get(i))) {
					if (add == false) {
						ori.remove(j);
					}
					continue newtags;
				}
			}
			if (add == true) {
				ori.add(newtags.get(i));
			}
		}
		return ori;
	}

	public synchronized void modifyTags(LinkedList<String> newtags, boolean add) {

		// comparar as duas listas e adicionar a this.tags os novos tags

		LinkedList<String> tagset = merge(newtags, add);
		tags.set(tagset);
		parser.modifyTags(tags);
		if (tagset.isEmpty()) {
			System.out.println("Clening up stream");
			stream.cleanup();

		} else {
			FilterQuery filter = new FilterQuery();
			filter.track(tagset.toArray(new String[] {}));
			try {
				TwitterListenner listener = new TwitterListenner(stack);
				stream.setStatusListener(listener);
				stream.filter(filter);
			} catch (TwitterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		System.out.println("Connection Mannager tags altered:");
		System.out.println(tags.getlistStack());
	}
}
